package com.mq.consumer.simple.v2;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;
import java.util.Set;

/**
 * @Classname CustomerProduce
 * @Description 指定位置消费
 * @Version 1.0.0
 * @Date 2025/3/7 9:53
 * @Created by ncs
 */
public class CustomConsumerSeek {

    static String kafkaServer = "192.168.125.100:9093,192.168.125.100:9094,192.168.125.100:9095";

    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaServer);
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "first-consumer");
        //指定位置消费 最早的位置
//        properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(properties);
        kafkaConsumer.subscribe(Collections.singleton("first-topic"));
        //分区信息
        Set<TopicPartition> assignment = kafkaConsumer.assignment();
        // 需要保证分区分配方案已经制定完毕
        while (assignment.isEmpty()) {
            kafkaConsumer.poll(Duration.ofSeconds(1));
            assignment = kafkaConsumer.assignment();
        }
        System.out.println("=============");
        for (TopicPartition topicPartition : assignment) {
            //指定offset
            kafkaConsumer.seek(topicPartition, 100);
        }
        while (true){
            ConsumerRecords<String, String> consumerRecords = kafkaConsumer.poll(Duration.ofMillis(20));
            consumerRecords.forEach(System.out::println);
        }
    }
}
